import Vue from 'vue'
import store from '@/store';

function baseRequest(url, method, data) {
	return new Promise((reslove, reject) => {
		uni.request({
			url: Vue.prototype.ENV_URl + 'index.php/' + url,
			method: method || 'GET',
			header: {
				'authorization': store.getters.userInfo.token,
				'Accept': 'application/json',
				'Content-Type': 'application/json; charset=utf-8'
			},
			timeout: 6000,
			data: data || {},
			success: (res) => {
				if (res.data.code === 2001) {
					store.commit('user/logout')
					Vue.prototype.goLogin()
				} else if (res.data.code !== 200) {
					uni.showToast({
						title: res.data.msg || res.massage || res,
						icon: "none",
						mask: true,
					})
				}
				reslove(res.data, res);
			},
			fail: () => {
				uni.showToast({
					title: '网络出错啦~',
					icon: "error"
				})
			}
		})
	});
}

const request = {};
['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});

export default request
